package cn.jh.clearing.service;

import java.math.BigDecimal;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import cn.jh.clearing.business.PaymentOrderBusiness;
import cn.jh.clearing.business.ProfitRecordBusiness;
import cn.jh.clearing.pojo.PaymentOrder;
import cn.jh.clearing.pojo.ProfitRecord;
import cn.jh.clearing.pojo.ProfitRecordExcel;
import cn.jh.clearing.util.Util;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.DownloadExcelUtil;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.RandomUtils;
import cn.jh.common.utils.TokenUtil;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class ProfitService {

	private static final Logger LOG = LoggerFactory.getLogger(ProfitService.class);

	@Autowired
	private ProfitRecordBusiness profitRecordBusiness;

	@Autowired
	private PaymentOrderBusiness paymentOrderBusiness;

	@Autowired
	Util util;

	/** 获取用户的分润明细 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/profit/query/{token}")
	public @ResponseBody Object pageProfitQuery(HttpServletRequest request, @PathVariable("token") String token,
			@RequestParam(value = "start_time", required = false) String startTime,
			@RequestParam(value = "end_time", required = false) String endTime,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		Map map = new HashMap();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
		Date StartTimeDate = null;
		if (startTime != null && !startTime.equalsIgnoreCase("")) {
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null;

		if (endTime != null && !endTime.equalsIgnoreCase("")) {
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}
		String grade = null;
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT,
				profitRecordBusiness.findProfitByUserid(userId + "", grade, StartTimeDate, endTimeDate, pageable));
		return map;
	}

	/** 获取用户的分润明细 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/profit/query/all")
	public @ResponseBody Object pageAllProfitQuery(HttpServletRequest request,
			// 用户手机号
			@RequestParam(value = "phone", defaultValue = "", required = false) String phone,
			// 用户编号
			@RequestParam(value = "userid", defaultValue = "0", required = false) long userid,
			// 起始时间
			@RequestParam(value = "start_time", required = false) String startTime,
			// 截止时间
			@RequestParam(value = "end_time", required = false) String endTime,
			// 贴牌id
			@RequestParam(value = "brand_id", defaultValue = "-1", required = false) long brandid,
			// 等级
			@RequestParam(value = "grade", required = false) String grade,
			// 身份证号
			@RequestParam(value = "idcard", required = false) String idcard,
			// 银行卡号
			@RequestParam(value = "cardNo", required = false) String cardNo,
			// 交易订单号
			@RequestParam(value = "orderCode", required = false, defaultValue = "") String orderCode,

			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		Map<String, Object> map = new HashMap<String, Object>();

		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
		Date StartTimeDate = null;
		if (startTime != null && !startTime.equalsIgnoreCase("")) {
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}else{
			StartTimeDate = DateUtil.getDateFromStr("1970-1-1");
		}
		Date endTimeDate = null;

		if (endTime != null && !endTime.equalsIgnoreCase("")) {
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}else{
			endTimeDate = new Date();
		}
		String userId = "";
		if (phone != null && !phone.equals("")) {
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/query/phone";
			/** 根据的用户手机号码查询用户的基本信息 */
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("phone", phone);
			requestEntity.add("brandId", brandid+"");
			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			JSONObject jsonObject = JSONObject.fromObject(result);
			JSONObject resultObj = jsonObject.getJSONObject("result");

			if (resultObj.containsKey("id")) {
				userId = resultObj.getString("id");
			} else {
				userId = "0";

			}
		}

		if (userid != 0) {
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/query/id";
			/** 根据的用户手机号码查询用户的基本信息 */
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("id", userid + "");
			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			JSONObject jsonObject = JSONObject.fromObject(result);
			JSONObject resultObj = jsonObject.getJSONObject("result");

			if (resultObj.containsKey("id")) {
				userId = resultObj.getString("id");
			} else {
				userId = "0";
			}
		}
		/***
		 * 身份证不为空判定
		 **/
		if (idcard != null && !idcard.equals("")) {

			/** 获取身份证实名信息 */
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/realname/idcard";

			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("idcard", idcard);
			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (result == null) {
				userId = "0";
			} else {
				userId = jsonObject.getString("userId");
			}
		}
		/***
		 * 银行卡不为空判定
		 **/
		if (idcard != null && !idcard.equals("")) {

			/** 获取银行卡信息 */
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/user/bank/default/cardno";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("cardno", cardNo);
			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (result == null) {
				userId = "0";
			} else {
				userId = jsonObject.getString("userId");
			}

		}

		Page<ProfitRecord> ProfitRecord = null;
		// 没贴牌ID
		if("".equals(orderCode)||null==orderCode){
			if (brandid == -1) {

				ProfitRecord = profitRecordBusiness.findProfitByUserid(userId, grade, StartTimeDate, endTimeDate, pageable);
			} else {

				ProfitRecord = profitRecordBusiness.findProfitByBrandId(brandid, userId, grade, StartTimeDate, endTimeDate,
						pageable);
			}
		}else{
			ProfitRecord = profitRecordBusiness.findProfitByUserid(orderCode, StartTimeDate, endTimeDate, pageable);
		}
		

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, ProfitRecord);
		return map;
	}

	/**
	 * 查询提现总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/profit/query/userid")
	public @ResponseBody Object findAllChannelByuserid(HttpServletRequest request,
			@RequestParam(value = "acq_user_id") long acquserid) {

		BigDecimal sumAcquserid = profitRecordBusiness.findsumProfitRecord(acquserid);

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT,
				sumAcquserid == null ? "0.00" : sumAcquserid.setScale(2, BigDecimal.ROUND_DOWN));
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/transactionclear/profit/query/byuserids")
	public @ResponseBody Object findAllChannelByUserIds(HttpServletRequest request,
			@RequestParam(value ="acqUserIds")String[] sacqUserIds
			){
		Map<String,Object>map = new HashMap<String, Object>();
		Map<String,Object>sumProfitMap = new HashMap<String, Object>();
		long [] acqUserIds = null;
		if(sacqUserIds.length>0){
			acqUserIds = new long[sacqUserIds.length];
			for(int i = 0;i < sacqUserIds.length;i++){
				acqUserIds[i] = Long.valueOf(sacqUserIds[i]);
			}
		}
		List<Object[]> models = profitRecordBusiness.findsumProfitRecordByAcqUserIds(acqUserIds);
		if(models!=null&&models.size()!=0){
			for(int i=0;i < models.size();i++){
				sumProfitMap.put(models.get(i)[0]+"", models.get(i)[1]);
			}
		}
//		map.put("models", sumProfitMap);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, sumProfitMap);
		return map;
		
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/queryall/profit")
	public @ResponseBody Object queryallProfit(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "ordercode",required=false) String order,
			@RequestParam(value = "phone",required=false) String phone,
			@RequestParam(value = "getphone",required=false) String getphone,
			@RequestParam(value = "strTime",required=false) String strTime,
			@RequestParam(value = "endTime",required=false) String endTime,
			@RequestParam(value = "type", required=false) String[] type,
			@RequestParam(value = "isDownload", defaultValue = "0", required = false) String isDownload,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "ordercode", required = false) String sortProperty){
		if(page < 0){
			page = 0;
		}
		if(size >1000){
			size = 1000;
		}else if("1".equals(isDownload)){
			size = 2000;
		}
		
		Map<String,Object> map = new HashMap<>();
		if("".equals(order))
			order = null;
		if("".equals(phone))
			phone = null;
		if("".equals(getphone))
			getphone = null;
		if("".equals(strTime))
			strTime = null;
		if("".equals(endTime))
			endTime = null;
		if(null==phone&&null==getphone&&null==order) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "参数不能为空");
			return map;
		}
		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
		Page<ProfitRecord> pageProfit = null;
		//List<ProfitRecord> listProfit = new ArrayList<ProfitRecord>();
		Date strdate = DateUtil.getDateFromStr("2016-01-01");
		Date enddate = new Date();
		if(null!=strTime)
			 strdate = DateUtil.getDateFromStr(strTime);
		if(null!=endTime)
			enddate = DateUtil.getDateFromStr(endTime);
		if(null==type||type.length==0) {
			type = new String[4];
			type[0] = "0";
			type[1] = "1"; 
			type[2] = "2"; 
			type[3] = "3";
		}
		if(null==phone&&null==getphone) {
			pageProfit = profitRecordBusiness.finByManyParams(order, type, strdate, enddate, pageable);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			return map;
		}
		if(null==order&&null==getphone) {
			List<PaymentOrder> list = paymentOrderBusiness.findPaymentOrderByTimeAndPhone(phone, strdate, enddate);
			if(list.size()==0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "此用户没有分润数据");
				return map;
			}
			String[] str = new String[list.size()];
			int i = 0;
			for(PaymentOrder po:list) {
				str[i] = po.getOrdercode();
				i++;
			}
			pageProfit = profitRecordBusiness.queryProfitAmountByPhone(phone, str,type,strdate, enddate, pageable);
			/*List<ProfitRecord> lis = pageProfit.getContent();
			List<ProfitRecord> liss = new ArrayList<ProfitRecord>();
			for(ProfitRecord pr:lis) {
				order = pr.getOrdercode();
				pageProfit = profitRecordBusiness.finByManyParams(order, type, strdate, enddate, pageable);
				List<ProfitRecord> lists = pageProfit.getContent();
				if(lists.size()>1) {
					liss.add(lists.get(0));
					for(int ii=1;ii<lists.size();ii++) {
						lists.get(ii).setOriphone(null);
						lists.get(ii).setOrirate(null);
						lists.get(ii).setAmount(null);
						liss.add(lists.get(ii));
					}
				}
			}
			Map mapp = new HashMap();
			mapp.put("content", liss);
			mapp.put("last", true);
			mapp.put("totalPages", 1+liss.size()/size);
			mapp.put("totalElements", liss.size());
			mapp.put("number", page);
			mapp.put("size", size);
			mapp.put("first", true);
			mapp.put("numberOfElements", liss.size());//此处liss.size()可能大于size
			List<Map> lil = new ArrayList<Map>();
			Map mam = new HashMap();
			mam.put("direction", "DESC");
			mam.put("property", "ordercode");
			mam.put("ignoreCase", false);
			mam.put("nullHandling", "NATIVE");
			mam.put("ascending", false);
			lil.add(mam);
			mapp.put("sort", lil);*/
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			
			return map;
		}
		if(null==order&&null==phone) {
			pageProfit = profitRecordBusiness.queryProfitAmountByGetPhone(getphone, type,strdate, enddate, pageable);
			Object obj = profitRecordBusiness.queryProfitAll(getphone, type, strdate, enddate, pageable);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			map.put("sum", obj);
			return map;
		}
		if(null==phone) {
			pageProfit = profitRecordBusiness.queryProfitAmountByOderGetPhone(getphone, order, type, strdate, enddate, pageable);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			return map;
		}
		if(null==getphone) {
			pageProfit = profitRecordBusiness.queryProfitAmountByOderPhone(phone, order, type, strdate, enddate, pageable);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			return map;
		}
		if(null==order) {
			pageProfit = profitRecordBusiness.queryProfitAmountByDoublePhone(phone, getphone, type, strdate, enddate, pageable);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, pageProfit);
			if("1".equals(isDownload)){
				if(pageProfit != null && pageProfit.getSize() >0){
					List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
					} catch (Exception e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败");
						return map;
					}
					if(downloadFile == null){
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
					return map;
				}
			}
			return map;
		}
		pageProfit = profitRecordBusiness.queryByAllParams(phone, getphone, order, type, strdate, enddate, pageable);
		if(null==pageProfit||!pageProfit.hasNext()) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "此笔订单没有产生分润");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, pageProfit);
		if("1".equals(isDownload)){
			if(pageProfit != null && pageProfit.getSize() >0){
				List<ProfitRecord> profitRecords = new ArrayList<>(pageProfit.getContent());
				String downloadFile;
				try {
					downloadFile = DownloadExcelUtil.downloadFile(request, response, profitRecords, new ProfitRecordExcel());
				} catch (Exception e) {
					e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "下载失败");
					return map;
				}
				if(downloadFile == null){
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
					return map;
				}else{
					map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
					map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
					map.put(CommonConstants.RESULT, downloadFile);
					return map;
				}
			}else{
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
				return map;
			}
		}
		return map;
	}
	/*
	 * 根据手机号和brandid查询分润额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/gradebrand/byphone")
	public @ResponseBody Object queryGradeBrandSchedule(HttpServletRequest request,
			// 用户手机号
			@RequestParam(value = "phone") String phone,
			// token
			@RequestParam(value = "brand_id") long brandid,
			// 起始时间
			@RequestParam(value = "start_time", required = false) String startTime,
			// 结束时间
			@RequestParam(value = "end_time", required = false) String endTime,
			// 用户订单号
			@RequestParam(value = "order_code", required = false) String ordercode,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction order,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sort) {
		Map map = new HashMap();
		Pageable pageable = new PageRequest(page, size, new Sort(order, sort));
		Date startTimeDate = null;
		if (startTime != null && !startTime.equalsIgnoreCase("")) {
			startTimeDate = DateUtil.getDateFromStr(startTime);
		} else {
			startTimeDate = DateUtil.getDateFromStr("2016-05-01");
		}
		Date endTimeDate = null;
		if (endTime != null && !endTime.equalsIgnoreCase("")) {
			endTimeDate = DateUtil.getDateFromStr(endTime);
		} else {
			endTimeDate = new Date();
		}
		try {
			if (phone != null && brandid != -1) {
				PaymentOrder paymentObject;
				List<ProfitRecord> AcqPhone;
				ProfitRecord profitObject;
				String oriphone;
				List<PaymentOrder> paymentpojo = paymentOrderBusiness.findOrderByphoneAndbrandid(phone, brandid,
						startTimeDate, endTimeDate, pageable);
				List<Map> listMap1 = null;
				List<Map> listMap2 = new ArrayList<Map>();
				Map map1 = null;
				for (int i = 0; i < paymentpojo.size(); i++) {
					listMap1 = new ArrayList<Map>();
					map1 = new HashMap();
					paymentObject = paymentpojo.get(i);
					phone = paymentObject.getPhone();
					ordercode = paymentObject.getOrdercode();
					map.put("phone", paymentObject.getPhone());
					map.put("rate", paymentObject.getRate());
					map1.put("amount", paymentObject.getAmount());
					map1.put("order", ordercode);
					List<ProfitRecord> listProfit = profitRecordBusiness.queryProfitAmount(ordercode);
					if (listProfit.size() == 0) {
						continue;
					}
					for (int j = 0; j < listProfit.size(); j++) {
						Map map2 = new HashMap();
						oriphone = phone;
						AcqPhone = profitRecordBusiness.queryProfitByOriPhone(oriphone, ordercode);
						if (AcqPhone.size() == 1) {
							profitObject = AcqPhone.get(0);
							map2.put("acqphone", profitObject.getAcqphone());
							map2.put("acqamount", profitObject.getAcqAmount());
							map2.put("acqrate", profitObject.getAcqrate());
							map2.put("remark", profitObject.getRemark());
							phone = profitObject.getAcqphone();
							listMap1.add(map2);
						} else {
							for (int k = 0; k < AcqPhone.size(); k++) {
								map2 = new HashMap();
								profitObject = AcqPhone.get(k);
								map2.put("acqphone", profitObject.getAcqphone());
								map2.put("acqamount", profitObject.getAcqAmount());
								map2.put("acqrate", profitObject.getAcqrate());
								map2.put("remark", profitObject.getRemark());
								phone = profitObject.getAcqphone();
								listMap1.add(map2);
							}
						}
						map1.put("brand", listMap1);
					}
					listMap2.add(map1);
				}
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "数据查询成功");
				map.put(CommonConstants.RESULT, listMap2);
			} else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
				map.put(CommonConstants.RESP_MESSAGE, "手机号不存在");
			}
		} catch (Exception e) {
			LOG.info(e.getMessage());
		}
		return map;
	}
	
	
	
	
	
	/** 获取用户的分润明细 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/profit/week")
	public @ResponseBody Object pageProfitQuery(HttpServletRequest request,
			@RequestParam(value = "start_time", defaultValue = "2018-03-05",  required = false) String startTime,
			@RequestParam(value = "end_time", defaultValue = "2018-03-19",  required = false) String endTime) {
		
		LOG.info("周提现分润结算");

		Date todayDate =null;

		SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");

		Date endDate = null;
		try {
			endDate = dft.parse(startTime);
			todayDate=dft.parse(endTime);
			
		} catch (ParseException e) {
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
		}
		//自清充值返利
		List<PaymentOrder> brandWithdrawClearRebates = paymentOrderBusiness.queryWeekBrandWithdrawClearRebate(endDate,todayDate);
		if(brandWithdrawClearRebates!=null) {
			LOG.info("RESULT===============日期="+endDate+"=======清算数量=" + brandWithdrawClearRebates.size());
			for (PaymentOrder withdrawRebate : brandWithdrawClearRebates) {
				
				ProfitRecord profitRecord=profitRecordBusiness.queryProfitRecordByordercode(withdrawRebate.getOrdercode(), 1+"");
				if(profitRecord!=null)
					continue;
				/*** 获取平台的管理员账号 */
				long brandid = withdrawRebate.getBrandid();
				String ordercode = withdrawRebate.getOrdercode();
				RestTemplate restTemplate = new RestTemplate();
				URI uri = util.getServiceUrl("user", "error url request!");
				String url = uri.toString()  + "/v1.0/user/brand/query/id?brand_id=" + brandid;
				String result = restTemplate.getForObject(url, String.class);
				/** 根据的渠道标识或去渠道的相关信息 */
				LOG.info("RESULT================" + result);
				JSONObject jsonObject = JSONObject.fromObject(result);
				if(!jsonObject.getString("resp_code").equals(CommonConstants.SUCCESS)){
					LOG.info("失败返利订单================" + withdrawRebate.getOrdercode()+"============brand_id==="+brandid);
					continue;
				}
				JSONObject resultObj = jsonObject.getJSONObject("result");
				String manageid = resultObj.getString("manageid");
				/** 根据manageid获取用户 */
				uri = util.getServiceUrl("user", "error url request!");
				url = uri.toString()  + "/v1.0/user/query/id";
				/** 根据的渠道标识或去渠道的相关信息 */
				MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("id", manageid);
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				if(!jsonObject.getString("resp_code").equals(CommonConstants.SUCCESS)){
					LOG.info("失败返利订单================" + withdrawRebate.getOrdercode()+"============manageid==="+manageid);
					continue;
				}
				resultObj = jsonObject.getJSONObject("result");
				String phone = resultObj.getString("phone");
				/** 根据订单号获取订单 */
				PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
				profitRecord = profitRecordBusiness.queryProfitRecordByordercode(ordercode, "1");
				if (profitRecord != null) {
					continue;
				} else {
					BigDecimal AcqAmount=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN) ;
					try {
						AcqAmount=paymentOrder.getExtraFee().subtract(paymentOrder.getCostfee()).setScale(2, BigDecimal.ROUND_DOWN);
					} catch (Exception e) {
						LOG.info("RESULT=============getExtraFee===" + paymentOrder.getExtraFee()+"====================getCostfee==="+paymentOrder.getCostfee());
						continue;
					}
					if(AcqAmount.compareTo(new BigDecimal("0.00"))<=0) {
						continue;
					}
					/** 存贮分润记录明细 */
					profitRecord = new ProfitRecord();
					profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
					profitRecord.setAcqAmount(AcqAmount);
					profitRecord.setAcqphone(phone);
					profitRecord.setAcquserid(Long.parseLong(manageid));
					profitRecord.setAmount(paymentOrder.getAmount());
					profitRecord.setCreateTime(new Date());
					profitRecord.setOrdercode(ordercode);
					profitRecord.setOriphone(paymentOrder.getPhone());
					profitRecord.setOrirate(paymentOrder.getRate());
					profitRecord.setOriuserid(paymentOrder.getUserid());
					profitRecord.setRemark("品牌自清分润");
					profitRecord.setType("1");
					profitRecord.setScale(BigDecimal.ONE);
					profitRecordBusiness.merge(profitRecord);
					/** 存储 用户的分润记录 */ 
					try {
						restTemplate = new RestTemplate();
						uri = util.getServiceUrl("user", "error url request!");
						url = uri.toString()  + "/v1.0/user/rebate/update";
						/** 根据的渠道标识或去渠道的相关信息 */
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("rebate_amount", AcqAmount.toString());
						requestEntity.add("user_id", manageid);
						requestEntity.add("order_code", ordercode);
						result = restTemplate.postForObject(url, requestEntity, String.class);
					}catch (Exception e) {
						LOG.info("RESULT===============返利疑似失败====================order_code==="+ordercode);
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						continue;
					}
					
				}
			}
		}
		return null;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
